// 上传文件到服务器
const { exec } = require('child_process');

let nodeSsh = null;

// const host = '120.76.114.178';// 测试环境
const host = '47.104.159.154';// 生产环境
// const port = 22; // 连接端口号(测试)
const port = 22197; // 连接端口号(生产)
const username = 'dev'; // 用户名
// const password = 'UiN$k329h6L';// 密码(测试)
const password = 'inYXk$67pTR97';// 密码(生产)
// const remotePath = '/opt/apache-tomcat-8.5.35/webapps/ROOT'; // 远程路径(测试)
const remotePath = '/data/workspace/prod_test_backend/webapps/ROOT'; // 远程路径(生产)
const distPath = './dist';// 本地需要上传的路径

function main(SSH) {
	console.log('正在连接ssh');
	const ssh = new SSH();
	ssh.connect({ host, username, password, port })
	.then(() => {
		console.log('连接成功，开始上传');
		const failed = [];
		const successful = [];
		ssh.putDirectory(distPath, remotePath, {
			recursive: true,
			concurrency: 5,
			validate(itemPath) {
				return true;
			},
			tick(localPath, remote, error) {
				if (error) {
					failed.push(localPath);
					console.log(`上传失败：${localPath}`);
				} else {
					console.log(`上传成功：${localPath}`);
					successful.push(localPath);
				}
			},
		}).then((status) => {
			console.log('目录上传', status ? '成功' : '失败');
			console.log(`上传失败：${failed.length}`, failed.join(',\n'));
			ssh.dispose();
		}).catch((err) => {
			console.log('上传出错', err);
			ssh.dispose();
		});
	});
}

try {
	nodeSsh = require('node-ssh');
	main(nodeSsh);
} catch (err) {
	console.log('没有安装node-ssh，正在自动安装node-ssh');
	console.log('npm install node-ssh -D');
	exec('npm install node-ssh -D', (error, stdout, stderr) => {
		if (error) {
			console.error(`安装失败了，可以试一下手动安装: ${error}`);
			return;
		}
		nodeSsh = require('node-ssh');
		if (nodeSsh) {
			console.log('node-ssh安装成功了');
		}
		main(nodeSsh);
	});
}

